// import { httpApi } from '@app-cad/server';
import { Form, Input, Modal, Select } from 'antd';
import React, { useEffect, useState } from 'react';
import { MessageTip, CMEVENTS } from '@amcax/base';
import { Picker3D, PickerMgr } from '@amcax/renderer';
import { httpApi } from '../../../../../../server';
import { userEvents } from '../../../../../../module';

export default function ComponentModal() {
  const Picker = PickerMgr.getPicker<Picker3D>('3d');
  const [open, setOpen] = useState<boolean>(false);
  const [name, setName] = useState<string>();
  const [loading, setLoading] = useState<boolean>(false);
  const [category, setCategory] = useState<string>('');
  const [categories, setCategories] = React.useState<any[]>([]);

  const [form] = Form.useForm();

  useEffect(() => {
    registerEvents();
  }, []);

  useEffect(() => {
    if (open) {
      loadCategories();
    }
  }, [open]);

  const registerEvents = () => {
    userEvents.on(CMEVENTS.COMPONENT_ADD_MODAL_SHOW, (dxid: string) => {
      console.log('ComponentModal show', dxid);
      setOpen(true);
    });
  };

  const loadCategories = async () => {
    const { data } = await httpApi.getComponentCategories();
    console.log('loadCategories', data);
    setCategories(data);
  };

  const handleCategoryChange = (value: string) => {
    console.log('category changed', value);
    setCategory(value);
  };
  const handleNameChange = (value: string) => {
    console.log('name changed', value);
    setName(value);
  };

  const handleOk = async () => {
    try {
      setLoading(true);
      const values = await form.validateFields();
      console.log('Success:', values);
      const { name, category } = values;
      const checkComponentNameParams = {
        name,
        category,
      };
      const { data } = await httpApi.checkComponentName(
        checkComponentNameParams,
      );
      if (data.available) {
        const selectedModels = Picker.getSelectedModels();
        if (selectedModels.size > 0) {
          const selectedModel = selectedModels.values().next().value;
          const createComponentParams = {
            projectUUID: 'ctx2.projectId',
            name,
            category,
            visibility: 'private',
            thumbnail: '',
            o: selectedModel.idInfo.o,
            a: {},
          };
          console.log('createComponentParams', createComponentParams);
          await httpApi.createComponent(createComponentParams);
          userEvents.emit(CMEVENTS.COMPONENT_ADDED);
          setOpen(false);
        }
      } else {
        MessageTip.error('构件名称已存在');
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    } finally {
      setLoading(false);
    }
  };
  const handleClose = () => {
    setOpen(false);
  };
  return (
    <Modal
      title='保存到构件库'
      open={open}
      onOk={handleOk}
      onCancel={handleClose}
      okText='保存'
      cancelText='取消'
      confirmLoading={loading}>
      <Form form={form}>
        <Form.Item
          label='构件类型'
          name='category'
          rules={[{ required: true, message: '请选择构件类型' }]}>
          <Select
            placeholder='请选择构件类型'
            onChange={handleCategoryChange}
            options={categories.map((item: any) => {
              return {
                value: item.id,
                label: item.name,
              };
            })}
          />
        </Form.Item>
        <Form.Item
          label='构件名称'
          name='name'
          rules={[{ required: true, message: '请输入构件名称' }]}>
          <Input
            placeholder='请输入构件名称'
            value={name}
            onChange={(e) => handleNameChange(e.target.value)}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
}
